import * as step from '@flow-step/step-toolkit'
import * as OSS from './oss-upload'
import * as fs from 'fs'
import * as util from './util'
import * as inputCheck from './input-check'
import * as upload from './package-upload'
import path from 'path'
import {PackInputs} from './pack-inputs'
import mdFile from 'md5-file'
import {UploadInputs} from './upload-inputs'
import * as uploadToPackageFile from './package-file-upload'

export async function execute(): Promise<void> {
    //打包
    let uploadInputs = await pack()
    //上传
    if (uploadInputs.uploadType === 'PACKAGES') {
        //上传packages
        await upload.artifactUpload(uploadInputs)
        await upload.uploadMetaData(uploadInputs)

    } else if (uploadInputs.uploadType === 'PACKAGE_FILE_STORAGE') {
        //专有云：上传到公共制品仓库
        await uploadToPackageFile.uploadToPackageFileStorage(uploadInputs)
    } else {
        //上传OSS
        await OSS.put(uploadInputs)
    }
}

export async function pack(): Promise<UploadInputs> {
    const input = await inputCheck.getInputs()
    let packageDir = input.workDir + util.SEP + 'packages'
    if (!fs.existsSync(packageDir)) {
        fs.mkdirSync(packageDir)
    } else {
        util.clearDir(packageDir)
    }

    // 打包
    let artifactFullName = ''
    const packInputs = {} as PackInputs
    packInputs.projectDir = input.projectDir
    if (input.filePath.indexOf(' ') != -1) {
        let arr: string[] = []
        for (let singlePath of input.filePath.split(' ')) {
            arr.push(singlePath)
        }
        packInputs.sourcePath = [...arr]
    } else {
        packInputs.sourcePath = [ input.filePath]
    }
    packInputs.filePath = input.filePath
    packInputs.gitIgnore = input.gitIgnore
    packInputs.includePathInArtifact = input.includePathInArtifact
    step.info(`Start to pack artifact`)
    if (step.platform.getPlatform() === step.platform.PLATFORM_WIN) {
        artifactFullName = packageDir + util.SEP + input.artifact + '.tar'
        packInputs.artifactFullName = artifactFullName
        packInputs.sevenZipLocation = path.join(
            path.resolve(__dirname, '..'),
            `src${util.SEP}binary${util.SEP}7zip${util.SEP}7z.exe`
        )
        step.info(`PackInputs, ${JSON.stringify(packInputs)}`)
        await util.sevenZipPack(packInputs)

    } else {
        artifactFullName = packageDir + util.SEP + input.artifactName
        packInputs.artifactFullName = artifactFullName
        step.info(`PackInputs, ${JSON.stringify(packInputs)}`)
        await util.tarPack(packInputs)
    }
    input.fileMD5 = mdFile.sync(`${artifactFullName}`)
    input.artifactFullName = artifactFullName
    return input
}
